package bdz.projects.lavender.opsm.utils {
	
	import bdz.common.events.*;
	import bdz.common.display.DisplayLoader;
	import bdz.projects.lavender.opsm.model.FlipCollection;
	import bdz.projects.lavender.opsm.vo.ProductVO;
	import bdz.projects.lavender.opsm.utils.ImageCache;
	import flash.display.Sprite;
	import flash.events.*;
	
	/**
	 * ...
	 * @author ...
	 */
	public class LoadChunker extends EventDispatcher {
		private var _loadItems:FlipCollection;
		private var _treshold:Number;
		private var _loadIndex:Number = 0;
		private var _loadTotal:Number;
		private var _imageCache:ImageCache;
		private var _paused:Boolean = false;
		private var _completed:Boolean = false;
		function LoadChunker() {
			
			_imageCache = ImageCache.getInstance();
		}
		private function getInitialChunk():void {
			if(!_completed){
				if(!_paused){
					_imageCache.getImage(_loadItems[_loadIndex].defaultImage, onImageLoaded);
				}else {
					_loadIndex--;
				}
			}
		}
		private function getRest():void {
			
			if(!_completed){
				if (!_paused) {	
					_imageCache.getImage(_loadItems[_loadIndex].defaultImage, onCachedImageLoaded);
				}else {
					_loadIndex--;
				}
			}
		}
		private function onCachedImageLoaded(evt:Event):void {
			if (_loadIndex < _loadTotal-1) {
				_loadIndex++;
				getRest();
			}else {
				_completed = true;
				dispatchEvent(new GenericEvent(GenericEvent.COMPLETE));
			}
		}
		public function start():void {
			if(_loadItems && _treshold){
				getInitialChunk();
				dispatchEvent(new GenericEvent(GenericEvent.LOAD_PROGRESS));
			}
			
		}
		private function onImageLoaded(evt:Event):void {
			if (_loadIndex < Math.ceil(_loadTotal * _treshold)) {
				_loadIndex++;
				getInitialChunk();
			}else {
				_paused = true;
				dispatchEvent(new GenericEvent(GenericEvent.PROGRESS_COMPLETE));
			}
		}
		public function resume():void {
			if (_paused) {
				_paused = false;
				_loadIndex++;
				getRest();
				
			}
		}
		public function pause():void {
			_paused = true;
		}
		public function get treshold():Number {
			return _treshold;
		}
		public function set treshold(n:Number):void {
			_treshold = n;
		}
		public function get loadItems():FlipCollection {
			return _loadItems;
		}
		public function set loadItems(arr:FlipCollection):void {
			_completed = false;
			_loadItems = arr;
			_loadTotal = _loadItems.length;
		}
		public function get paused():Boolean {
			return _paused;
		}
		
	}
	
}